import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import {getCookies} from '../utils/auth.js'
import Layout from '@/layout/index.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import("../views/login.vue"),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/register',
    name: 'register',
    component: () => import("../views/register.vue"),
    meta: {
      title: '注册'
    }
  },
  {
    path: '/home',
    name: 'home',
    redirect: '/home/news',
    component: Layout,
    children: [
      {
        path: '/user',
        name: 'user',
        component: () => import("@/views/user/index.vue"),
      },
      {
        path: 'file/:pid',
        name: 'file',
        component: () => import("@/views/file/index.vue"),
        meta: {
          title: '文件页'
        }
      },
      {
        path: 'news',
        name: 'news',
        component: () => import("@/views/news/index.vue"),
        meta: {
          title: '消息页'
        },
        children: [
          {
            path: 'chatDetail',
            name: 'chatDetail',
            component: () => import("@/views/news/chatDetail/index.vue")
          },
          {
            path: 'friendDetail',
            name: 'friendDetail',
            component: () => import("@/views/news/friendDetail/index.vue")
          }
        ]
      },
      {
        path: 'calendar',
        name: 'calendar',
        component: () => import("@/views/calendar/index.vue"),
        meta: {
          titlle: '日历页'
        }
      },
      {
        path: 'coEdit',
        name: 'coEdit',
        component: () => import("@/views/coEdit/index.vue"),
        meta: {
          titlle: '协同编辑页'
        }
      },
      {
        path: 'editBox',
        name: 'editBox',
        component: () => import("@/views/editBox/index.vue"),
        meta: {
          titlle: '文档编辑框页'
        },
      },
    ]
  
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  if(to.path == '/login' || to.path == '/register') {
    next()
  } else {
    let token = getCookies('token')
    if(token == null || token == '') {
      next('/login')
    } else {
      next()
    }
  }
})

export default router
